package Controller;

import Entity.Users;
import Service.UsersService;
import Util.CookieSave;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/*
处理登录新闻
 */
@WebServlet(name = "Controller.LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        //Login的处理
        try {
            Login(request,response);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    void Login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        //获取表单中的数据的值
        Users user=new Users();
        user.setName(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        System.out.println("登入用户名："+user.getName());
        System.out.println("登入用户密码："+user.getPassword());
        System.out.println("-------------------------------");
        //验证用户名密码
        UsersService usersService=new UsersService();
        boolean hasUsers=usersService.QueryUsers(user);
        if(hasUsers){
            CookieSave cookieSave=new CookieSave();
            cookieSave.Save(response,"username",user.getName(),60*60*24*30);
            cookieSave.Save(response,"password",user.getPassword(),60*60*24*30);
            //成功登录，进入管理主界面
            response.sendRedirect("yinglang/index.html");
        }else
        {
            response.getWriter().println("登陆失败");
            //登录失败，返回登陆界面
            response.sendRedirect("index.jsp");
        }
    }
}